package xml.utils;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class XMLUtil {
    //获取document对象
    public Document getDocument(String src) throws ParserConfigurationException, IOException, SAXException {
        //创建DOM解析器的工厂实例
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //从DOM工厂获取DOM解析器
        DocumentBuilder builder = factory.newDocumentBuilder();
        //解析XML文档，得到一个Document对象，即DOM树
        Document document = builder.parse(src);
        //返回Document对象
        return document;
    }
    //保存XML文件
    public void saveXMLFile(Document document,String src) throws Exception{
        //保存XML文件
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        //设置编码格式
        transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
        StreamResult result = new StreamResult(new FileOutputStream(src));
        //把DOM树转换为XML文件
        transformer.transform(domSource,result);
    }
}
